package com.heihei.util;

import com.heihei.constant.MessageConstant;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 *  java调用命令行
 *
 * @version 1.0
 * @since JDK1.8
 * @author duanhengfei
 * @date 2021年01月28日 09:35:22
 */
public class CommandUtil {
    public static void exeCmd(String commandStr) {
        if(commandStr.startsWith(MessageConstant.NOT_CMD_COMMAND)) {
            System.out.println(commandStr.substring(MessageConstant.NOT_CMD_COMMAND.length()));
            return;
        }
        BufferedReader br = null;
        try {
            Process p = Runtime.getRuntime().exec(commandStr);
            br = new BufferedReader(new InputStreamReader(p.getInputStream(), "GBK"));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            System.out.println(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (br != null)
            {
                try {
                    br.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}